package samples.chapter10;


import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class Chapter10WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    Chapter10UserService userService;

    @Bean
    PasswordEncoder chapter10PasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    RoleHierarchy chapter10RoleHierarchy() {
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
        roleHierarchy.setHierarchy("ROLE_DBA > ROLE_ADMIN > ROLE_USER");
        return roleHierarchy;
    }

    @Bean
    Chapter10FilterInvocationSecurityMetadataSource chapter10Fisms() {
        return new Chapter10FilterInvocationSecurityMetadataSource();
    }

    @Bean
    Chapter10AccessDecisionManger chapter10Adm() {
        return new Chapter10AccessDecisionManger();
    }

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    // @Override
    // protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //     auth.inMemoryAuthentication()
    //             .withUser("root").password("123456").roles("ADMIN", "DBA")
    //             .and()
    //             .withUser("admin").password("123456").roles("ADMIN", "USER")
    //             .and()
    //             .withUser("user").password("123456").roles("USER");
    // }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/chapter10/admin/**").hasRole("ADMIN")
                .antMatchers("/chapter10/user/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/chapter10/db/**").hasAnyRole("DBA", "ADMIN")
                .anyRequest().permitAll()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setSecurityMetadataSource(chapter10Fisms());
                        object.setAccessDecisionManager(chapter10Adm());
                        return object;
                    }
                })
                .and()
                .formLogin()
                .loginPage("/chapter10/login")
                .loginProcessingUrl("/chapter10/login")
                .usernameParameter("name")
                .passwordParameter("passwd")
                .successHandler((httpServletRequest, httpServletResponse, authentication) -> {
                    Object principal = authentication.getPrincipal();
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    PrintWriter writer = httpServletResponse.getWriter();
                    httpServletResponse.setStatus(200);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("status", 200);
                    map.put("msg", principal);
                    Gson objectMapper = new Gson();
                    writer.write(objectMapper.toJson(map));
                    writer.flush();
                    writer.close();
                })
                .failureHandler((httpServletRequest, httpServletResponse, e) -> {
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    httpServletResponse.setStatus(401);
                    PrintWriter writer = httpServletResponse.getWriter();
                    HashMap<Object, Object> map = new HashMap<>();
                    map.put("status", 401);
                    if (e instanceof LockedException) {
                        map.put("msg", "账户被锁定，登录失败！");
                    } else if (e instanceof BadCredentialsException) {
                        map.put("msg", "账户名或密码输入错误，登录失败！");
                    } else if (e instanceof DisabledException) {
                        map.put("msg", "账户被禁用，登录失败！");
                    } else if (e instanceof AccountExpiredException) {
                        map.put("msg", "账户已过期，登录失败！");
                    } else if (e instanceof CredentialsExpiredException) {
                        map.put("msg", "密码已过期，登录失败！");
                    } else {
                        map.put("msg", "登录失败！");
                    }
                    Gson objectMapper = new Gson();
                    writer.write(objectMapper.toJson(map));
                    writer.flush();
                    writer.close();
                })
                .and()
                .logout()
                .logoutUrl("/chapter10/logout")
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .addLogoutHandler((httpServletRequest, httpServletResponse, authentication) -> {

                })
                .logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication)
                        -> httpServletResponse.sendRedirect("/chapter10/login"))
                .and()
                .antMatcher("/chapter10/oauth/**").authorizeRequests()
                .antMatchers("/chapter10/oauth/**").permitAll()
                .and()
                .csrf()
                .disable();
    }
}
